package com.vlin.controller.scheduler;

import java.util.List;

import org.json.JSONObject;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.vlin.service.ScheService;
import com.vlin.service.schedule.ScheduleService;

@RestController
public class SchedulerController implements ScheduleService {

	
	private static final Logger logger = LoggerFactory.getLogger(SchedulerController.class);
	
	@Autowired
	private Scheduler scheduler;
	
	@Autowired
	private List<ScheService> scheList;

	@Override
	public String addScheduler(String cron, String autoId, String serviceId) {
		Class<? extends Job> job = null;
		JSONObject result = new JSONObject();
		if (scheList != null) {
			for (ScheService service : scheList) {
				if (service.support(serviceId)) {
					job = service.job();
				}
			}
		}

		if (job == null) {
			result.put("result", "fail");
			return result.toString();
		}

		JobDetail job1 = JobBuilder.newJob(job).withIdentity(serviceId + ":job:" + autoId, serviceId).build();


		
		CronTrigger cronTrigger = TriggerBuilder.newTrigger()
        .withIdentity(serviceId + ":trigger:" + autoId, serviceId)
        .startNow()
        .withSchedule(CronScheduleBuilder.cronSchedule(cron))            
        .build();
		try {
			scheduler.scheduleJob(job1, cronTrigger);
			logger.info("{},{},{} schedule", cron, autoId, serviceId);
		} catch (SchedulerException e) {
			logger.error("{},{},{} schedule exception {}", cron, autoId, serviceId, e);
			e.printStackTrace();
		}
		
		result.put("result", "success");
		return result.toString();
	}
	
	@RequestMapping("test")
	public String test() {
		
		return "test";
	}
	
	

}
